package image_api

import (
	"fastgin/global"
	"fastgin/utils/find"
	"fastgin/utils/md5image"
	"fastgin/utils/res"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

// 图片白名单
var whiteList = []string{
	".jpg",
	".jpeg",
	".png",
	".webp",
}

func (ImageApi) UploadView(c *gin.Context) {
	fileHeader, err := c.FormFile("file")
	if err != nil {
		res.FailWithMsg("请选择文件", c)
		return
	}
	//图片不能大于2M
	if fileHeader.Size > global.Config.Upload.Size*1024*1024 {
		res.FailWithMsg("上传文件过大", c)
		return
	}
	//后缀判断
	ext := strings.ToLower(filepath.Ext(fileHeader.Filename))
	if !find.InList(whiteList, ext) {
		res.FailWithMsg("文件后缀不符合要求", c)
		return
	}
	//处理文件名重复
	fp := path.Join("uploads", global.Config.Upload.Dir, fileHeader.Filename)
	for {
		_, err1 := os.Stat(fp)
		if os.IsNotExist(err1) {
			break
		}
		uploadFile, _ := fileHeader.Open()
		oldFile, _ := os.Open(fp)
		uploadFileHash := md5image.MD5WithFile(uploadFile)
		oldFileHash := md5image.MD5WithFile(oldFile)
		if uploadFileHash == oldFileHash {
			//上传的图片 名称和内容都是一样的
			return
		}
		//上传的图片 名称一样 但内容不同
		fileNameNotExt := strings.TrimSuffix(fileHeader.Filename, ext)
		newFileName := fmt.Sprintf("%s_%s%s", fileNameNotExt, md5image.RandStr(3), ext)
		fp = path.Join("uploads", global.Config.Upload.Dir, newFileName)
	}
	c.SaveUploadedFile(fileHeader, fp)
	res.Ok("/"+fp, "上传成功", c)
}
